package com.ghp.search.datasource;

import com.ghp.search.model.enums.SearchTypeEnum;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ghp
 * @date 2023/5/31
 * @title
 * @description
 */
@Component
public class DataSourceRegistry {

    @Resource
    private PostDataSource postDataSource;

    @Resource
    private PictureDataSource pictureDataSource;

    @Resource
    private UserDataSource userDataSource;

    private Map<String, DataSource<T>> typeDataSourceMap;

    /**
     * 初始化DataSource
     *
     * 注意：@PostConstruct标识的方法是在依赖注入后调用，
     * 如果直接使用new来初始化，会导致DataSource初始化失败
     * 因为成员变量的赋值是发生在依赖注入之前的
     */
    @PostConstruct
    private void init() {
        typeDataSourceMap = new HashMap() {{
            put(SearchTypeEnum.POST.getValue(), postDataSource);
            put(SearchTypeEnum.USER.getValue(), userDataSource);
            put(SearchTypeEnum.PICTURE.getValue(), pictureDataSource);
        }};
    }

    /**
     * 根据类型获取对应的DataSource对象
     *
     * @param type
     * @return
     */
    public DataSource getDataSourceByType(String type) {
        if (type == null){
            // 健壮性保障
            return null;
        }
        return typeDataSourceMap.get(type);
    }

}
